package com.kexilo.system.system.controller;

import com.kexilo.core.common.annotation.Debounce;
import com.kexilo.core.common.annotation.Idempotent;
import com.kexilo.core.common.annotation.Log;
import com.kexilo.core.common.core.page.TableDataInfo;
import com.kexilo.core.common.core.web.BaseController;
import com.kexilo.core.common.core.web.domain.R;
import com.kexilo.core.common.enums.BusinessType;
import com.kexilo.core.common.utils.SecurityUtils;
import com.kexilo.core.system.domain.SysConfig;
import com.kexilo.system.system.service.ISysConfigService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 参数配置 信息操作处理
 * 
 * @author Kexilo
 */
@RestController
@RequestMapping("/system/config")
@Tag(name = "参数配置管理", description = "参数配置信息管理相关接口")
public class SysConfigController extends BaseController {
    
    private static final Logger log = LoggerFactory.getLogger(SysConfigController.class);
    
    @Autowired
    private ISysConfigService configService;

    /**
     * 获取参数配置列表
     */
    @PreAuthorize("@ss.hasPermi('system:config:list')")
    @GetMapping("/list")
    @Operation(summary = "获取参数配置列表", description = "获取参数配置列表信息")
    @ApiResponses({
        @ApiResponse(responseCode = "200", description = "获取成功"),
        @ApiResponse(responseCode = "403", description = "权限不足")
    })
    public TableDataInfo list(SysConfig config) {
        startPage();
        List<SysConfig> list = configService.selectConfigList(config);
        return getDataTable(list);
    }

    @Debounce(interval = 10, message = "导出操作过于频繁，请稍后再试")
    @Log(title = "参数管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:config:export')")
    @PostMapping("/export")
    @Operation(summary = "导出参数配置", description = "导出参数配置数据")
    public R<Void> export(SysConfig config) {
        List<SysConfig> list = configService.selectConfigList(config);
        // TODO: 实现导出功能
        return success();
    }

    /**
     * 根据参数编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:config:query')")
    @GetMapping(value = "/{configId}")
    @Operation(summary = "获取参数配置详情", description = "根据参数配置ID获取详细信息")
    public R<SysConfig> getInfo(@Parameter(description = "参数配置ID") @PathVariable Long configId) {
        return success(configService.selectConfigById(configId));
    }

    /**
     * 根据参数键名查询参数值
     */
    @GetMapping(value = "/configKey/{configKey}")
    @Operation(summary = "根据参数键名查询参数值", description = "根据参数键名获取参数值")
    public R<String> getConfigKey(@Parameter(description = "参数键名") @PathVariable String configKey) {
        return R.success(configService.selectConfigByKey(configKey));
    }

    /**
     * 新增参数配置
     */
    @PreAuthorize("@ss.hasPermi('system:config:add')")
    @Log(title = "参数管理", businessType = BusinessType.INSERT)
    @Debounce(strategy = Debounce.Strategy.REQUEST_PARAMS, interval = 5, message = "请勿重复提交参数配置信息")
    @Idempotent(strategy = Idempotent.Strategy.REQUEST_PARAMS, key = "#config.configKey", timeout = 5, message = "该参数配置正在处理中，请稍后再试")
    @PostMapping
    @Operation(summary = "新增参数配置", description = "新增参数配置信息")
    public R<Void> add(@Validated @RequestBody SysConfig config) {
        if (!configService.checkConfigKeyUnique(config)) {
            return error("新增参数'" + config.getConfigName() + "'失败，参数键名已存在");
        }
        config.setCreateBy(SecurityUtils.getUsername());
        return toAjax(configService.insertConfig(config));
    }

    /**
     * 修改参数配置
     */
    @PreAuthorize("@ss.hasPermi('system:config:edit')")
    @Log(title = "参数管理", businessType = BusinessType.UPDATE)
    @Debounce(strategy = Debounce.Strategy.REQUEST_PARAMS, interval = 3, message = "请勿频繁修改参数配置信息")
    @Idempotent(strategy = Idempotent.Strategy.REQUEST_PARAMS, key = "#config.configId", timeout = 3, message = "参数配置信息正在更新中，请稍后再试")
    @PutMapping
    @Operation(summary = "修改参数配置", description = "修改参数配置信息")
    public R<Void> edit(@Validated @RequestBody SysConfig config) {
        if (!configService.checkConfigKeyUnique(config)) {
            return error("修改参数'" + config.getConfigName() + "'失败，参数键名已存在");
        }
        config.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(configService.updateConfig(config));
    }

    /**
     * 删除参数配置
     */
    @PreAuthorize("@ss.hasPermi('system:config:remove')")
    @Log(title = "参数管理", businessType = BusinessType.DELETE)
    @Debounce(strategy = Debounce.Strategy.USER_METHOD, interval = 5, message = "删除操作过于频繁，请稍后再试")
    @Idempotent(strategy = Idempotent.Strategy.REQUEST_PARAMS, timeout = 5, delKey = true, message = "删除操作正在进行中，请勿重复操作")
    @DeleteMapping("/{configIds}")
    @Operation(summary = "删除参数配置", description = "删除参数配置信息")
    public R<Void> remove(@Parameter(description = "参数配置ID数组") @PathVariable Long[] configIds) {
        configService.deleteConfigByIds(configIds);
        return success();
    }

    /**
     * 刷新参数缓存
     */
    @PreAuthorize("@ss.hasPermi('system:config:remove')")
    @Log(title = "参数管理", businessType = BusinessType.CLEAN)
    @DeleteMapping("/refreshCache")
    @Operation(summary = "刷新参数缓存", description = "清空并重新加载参数缓存")
    public R<Void> refreshCache() {
        configService.resetConfigCache();
        return success();
    }
}
